package HASH_TABLE

import (
	"strconv"
	"strings"
)

//// 排序法
//func groupAnagrams(strs []string) [][]string {
//	groupMap := make(map[string][]string)
//	for _, s := range strs {
//		sBytes := []byte(s)
//		sort.Slice(sBytes, func(i, j int) bool {
//			return sBytes[i] < sBytes[j]
//		})
//		key := string(sBytes)
//		groupMap[key] = append(groupMap[key], s)
//	}
//	result := make([][]string, 0, len(groupMap))
//	for _, group := range groupMap {
//		result = append(result, group)
//	}
//	return result
//}

// 计数哈希法
func groupAnagrams(strs []string) [][]string {
	groupMap := make(map[string][]string)
	for _, s := range strs {
		count := [26]int{}
		for _, c := range s {
			idx := c - 'a'
			count[idx]++
		}
		var keyBuilder strings.Builder
		for i, v := range count {
			if i > 0 {
				keyBuilder.WriteString(",")
			}
			keyBuilder.WriteString(strconv.Itoa(v))
		}
		key := keyBuilder.String()
		groupMap[key] = append(groupMap[key], s)
	}
	result := make([][]string, 0, len(groupMap))
	for _, group := range groupMap {
		result = append(result, group)
	}
	return result
}
